package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.ram.model.v20150501.DeleteAccessKeyRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.util.AliyunVodSDKUtils;
import com.atguigu.vod.util.ConstantVodUtils;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
//@CrossOrigin
public class VodController {
    @Autowired
    private VodService vodService;
    //上传视频到阿里云
    @PostMapping("uploadVideoAly")
    public R uploadVideoAly(MultipartFile file){
        String videoId = vodService.uploadVideoAly(file);
        return R.ok().data("videoId",videoId);
    }
    //删除视频
    @DeleteMapping("{videoId}")
    public R deleteVideoAly(@PathVariable String videoId){
        try {
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建request和response对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            DeleteVideoResponse response = client.getAcsResponse(request);
            return R.ok();
        }catch (Exception e) {
            e.printStackTrace();
            return R.error().message("删除视频失败");
        }
    }
    //删除多个视频
    @DeleteMapping("delete-batch")
    public R removeVideoList(@RequestParam("videoIdList") List<String> videoIdList){
        vodService.removeVideoList(videoIdList);
        return R.ok();
    }
    //获取视频播放凭证
    @GetMapping("getPlayAuth/{vodId}")
    public R getPlayAuth(@PathVariable String vodId){
        try {
            //初始化
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建request response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //设置视频id
            request.setVideoId(vodId);
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            //获取凭证
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        } catch (Exception e) {
            throw new GuLiException(20001,"获取视频凭证失败");
        }
    }
}
